import 'package:flutter/material.dart';
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import '../../utils/G.dart';

class Register extends StatefulWidget {
  const Register({Key? key}) : super(key: key);

  @override
  _RegisterState createState() => _RegisterState();
}

class _RegisterState extends State<Register> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String _phone = ''; // 手机号
  String _captcha = ''; // 验证码
  String _captchaText = '获取验证码';
  bool _isSent = false;

  late Timer _timer;
  int _counter = 60;
  String _verifyCode = "";

  @override
  void initState() {
    super.initState();
    // 获取发送短信的凭证
    _getVerifyCode();
  }

  void _getVerifyCode() async {
    var res = await G.api.user.verifyCode();
    if (res['status'] == 200) {
      _verifyCode = res['data']['key'];
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('快速登录'),
          centerTitle: true,
        ),
        body: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          padding: const EdgeInsets.all(20),
          physics: const BouncingScrollPhysics(),
          child: Column(
            children: [
              // 顶部 Logo
              const SizedBox(
                height: 40,
              ),
              Center(
                child: Image.asset(
                  'assets/images/logo.png',
                  width: 200,
                  height: 50,
                ),
              ),
              const SizedBox(
                height: 60,
              ),

              // 表单
              _renderRegisterForm(),

              // 页脚
              G.footer()
            ],
          ),
        ));
  }

  Widget _renderRegisterForm() {
    return Form(
        key: _formKey,
        child: Column(
          children: [
            TextFormField(
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                    prefixIcon: const Icon(Icons.phone),
                    fillColor: Colors.deepPurple.shade100,
                    filled: true,
                    border: InputBorder.none,
                    hintText: '手机号'),
                validator: (value) {
                  RegExp reg = RegExp(r'^\d{11}$');
                  if (!reg.hasMatch(value!)) {
                    return '手机号非法';
                  }
                  return null;
                },
                onChanged: (value) {
                  _phone = value.toString();
                }),
            const SizedBox(
              height: 10,
            ),
            TextFormField(
                keyboardType: TextInputType.number,
                decoration: InputDecoration(
                    prefixIcon: const Icon(Icons.password),
                    fillColor: Colors.deepPurple.shade100,
                    filled: true,
                    border: InputBorder.none,
                    hintText: '验证码',
                    suffixIcon: TextButton(
                        onPressed: _captchaCallback(),
                        child: Text(_captchaText))),
                validator: (value) {
                  return value!.isEmpty ? "请输入验证码" : null;
                },
                onChanged: (value) {
                  _captcha = value.toString();
                }),
            const SizedBox(
              height: 10,
            ),
            Row(
              children: [
                Expanded(
                    child: ElevatedButton(
                        onPressed: () async {
                          if (_formKey.currentState?.validate() as bool) {
                            // print(_phone+_captcha);

                            // 重置倒计时
                            _resetCountDown();

                            // 调用登陆接口
                            var res = await G.api.user
                                .register(phone: _phone, captcha: _captcha);
                            if (res['status'] == 200) {
                              // 保存用户的登陆状态
                              _saveUserToken(res['data']);

                              // 跳转到个人中心
                              Future.delayed(const Duration(milliseconds: 500),
                                  () {
                                G.router.navigateTo(context, '/mine');
                              });
                            } else {
                              // G.error(res['msg']);
                              G.error('登录失败');
                            }
                          }
                        },
                        child: const Text('登录'),
                        style: ButtonStyle(
                            padding: MaterialStateProperty.all(
                                const EdgeInsets.all(12)))))
              ],
            ),
            const SizedBox(
              height: 10,
            ),
            Row(
              children: [
                Expanded(
                    child: ElevatedButton(
                        onPressed: () async {
                          G.router.navigateTo(context, '/login');
                        },
                        child: const Text('账号登录'),
                        style: ButtonStyle(
                            padding: MaterialStateProperty.all(
                                const EdgeInsets.all(12)),
                            backgroundColor: MaterialStateProperty.all(
                                Colors.deepPurple.shade200))))
              ],
            )
          ],
        ));
  }

  _captchaCallback() {
    // 如果验证码已经发送，则倒计时效果，不能再点击
    if (_isSent) {
      // 按钮的回调函数为 null，则按钮不可点击
      return null;
    } else {
      return () async {
        // 验证手机号的合法性
        RegExp reg = RegExp(r'^\d{11}$');
        if (reg.hasMatch(_phone)) {
          // 倒计时
          countDown();

          // 发送验证码
          // @todo 调用发送验证码接口
          var res = await G.api.user
              .sendCaptcha(phone: _phone, key: _verifyCode, type: 'login');
          if (res['status'] == 200) {
            _isSent = true;
            // 提示框
            G.success('发送成功');
          } else {
            // 提示框
            G.error('发送失败');
          }
        } else {
          G.error('手机号非法');
        }
      };
    }
  }

  countDown() {
    var _duration = const Duration(seconds: 1);

    Timer(_duration, () {
      _timer = Timer.periodic(_duration, (timer) {
        _counter--;
        if (_counter == 0) {
          _resetCountDown();
        } else {
          setState(() {
            _captchaText = "剩余 " + _counter.toString() + " 秒";
          });
        }
      });
    });
  }

  void _resetCountDown() {
    setState(() {
      _timer.cancel();
      _isSent = false;
      _counter = 60;
      _captchaText = "获取验证码";
    });
  }

  _saveUserToken(Map res) async {
    // 获取保存实例
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('token', res['token']);
    await prefs.setInt('expires_time', res['expires_time']);
  }
}
